package com.jeecg.demo.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.jeecg.demo.entity.CwInoutmoneyEntity;
import com.jeecg.demo.entity.TraderEntity;
import com.jeecg.demo.service.CwInoutmoneyServiceI;
import com.jeecg.demo.service.SettlementServiceI;

/**
 * @Title: Controller
 * @Description: CW_INOUTMONEY
 * @author onlineGenerator
 * @date 2021-01-30 10:45:48
 * @version V1.0
 * 
 */
@Controller
@RequestMapping("/cwInoutmoneyController")
public class CwInoutmoneyController extends BaseController {
    private static final Logger logger = LoggerFactory
            .getLogger(CwInoutmoneyController.class);

    @Autowired
    private CwInoutmoneyServiceI cwInoutmoneyService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private SettlementServiceI settlementServiceI;

    /**
     * CW_INOUTMONEY列表 页面跳转
     * 
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("com/jeecg/demo/cwInoutmoneyList");
    }

    /**
     * easyui AJAX请求数据
     * 
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CwInoutmoneyEntity.class, dataGrid);
        // 查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                cwInoutmoney, request.getParameterMap());
        try {
            // 自定义追加查询条件
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cwInoutmoneyService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除CW_INOUTMONEY
     * 
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        cwInoutmoney = systemService.getEntity(CwInoutmoneyEntity.class,
                cwInoutmoney.getId());
        message = "删除成功";
        try {
            cwInoutmoneyService.delete(cwInoutmoney);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除CW_INOUTMONEY
     * 
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                CwInoutmoneyEntity cwInoutmoney = systemService.getEntity(
                        CwInoutmoneyEntity.class, Integer.parseInt(id));
                cwInoutmoneyService.delete(cwInoutmoney);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加CW_INOUTMONEY
     * 
     * @param ids
     * @return
     */
    /*
     * @RequestMapping(params = "doAdd")
     * 
     * @ResponseBody public AjaxJson doAdd(CwInoutmoneyEntity cwInoutmoney,
     * HttpServletRequest request) { String message = null; AjaxJson j = new
     * AjaxJson(); message = "CW_INOUTMONEY添加成功"; try{
     * cwInoutmoneyService.save(cwInoutmoney); systemService.addLog(message,
     * Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); }catch(Exception e){
     * e.printStackTrace(); message = "CW_INOUTMONEY添加失败"; throw new
     * BusinessException(e.getMessage()); } j.setMsg(message); return j; }
     */

    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CwInoutmoneyEntity cwInoutmoney, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        String mess = "";
        try {
            if ("0".equals(cwInoutmoney.getInouttype())) {
                mess = "出金";
            }
            else {
                mess = "入金";
            }
            String results = doInOut(cwInoutmoney);
            if ("success".equals(results)) {
                cwInoutmoneyService.save(cwInoutmoney);
                message = mess + "成功";
            }
            else {
                message = mess + "失败," + results;
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            message = mess + "失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    private String doInOut(CwInoutmoneyEntity cwInoutmoney) throws Exception {
        String inouttype = cwInoutmoney.getInouttype();
        String methond = "";
        Map<String, Object> map = new HashMap();
        String traderbank = cwInoutmoney.getTraderbank();
        String reqmoeny = cwInoutmoney.getReqmoeny();
        String tradercode = cwInoutmoney.getTradercode();
        String reqseqno = cwInoutmoney.getReqseqno();
        Date reqtime = cwInoutmoney.getReqtime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(reqtime);

        String moneypsd = "111111";
        List<TraderEntity> list = systemService.findByProperty(
                TraderEntity.class, "tradecode", tradercode);
        if (list.size() > 0) {
            moneypsd = list.get(0).getMoneypsd();
        }

        map.put("bankid", traderbank);
        map.put("zjmm", moneypsd);
        map.put("jine", reqmoeny);
        map.put("jysid", tradercode);
        map.put("seqno", reqseqno);
        String[] split = time.split(" ");
        map.put("jyrq", split[0]);
        map.put("jysj", split[1]);
        String params = JSON.toJSONString(map);
        if ("0".equals(inouttype)) {
            methond = "outMoney";
        }
        else {
            methond = "inMoney";
        }
        return settlementServiceI.doSettlement(params, methond);
    }

    /**
     * 更新CW_INOUTMONEY
     * 
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        CwInoutmoneyEntity t = cwInoutmoneyService.get(
                CwInoutmoneyEntity.class, cwInoutmoney.getId());
        boolean flag = true;
        String mess = "更新";
        try {
            message = mess + "失败";
            String inouttype = t.getInouttype();
            String inouttype2 = cwInoutmoney.getInouttype();
            if (StringUtils.isNotEmpty(inouttype)) {
                if (inouttype.equals(inouttype2)) {
                    flag = !cwInoutmoney.equals(t);
                }
                else {
                    if ("0".equals(cwInoutmoney.getInouttype())) {
                        mess = "出金";
                    }
                    else {
                        mess = "入金";
                    }
                    String results = doInOut(cwInoutmoney);
                    if ("success".equals(results)) {
                        flag = true;
                    }
                    else {
                        flag = false;
                        message = mess + "失败," + results;
                    }
                }
            }
            if (flag) {
                MyBeanUtils.copyBeanNotNull2Bean(cwInoutmoney, t);
                cwInoutmoneyService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE,
                        Globals.Log_Leavel_INFO);
                message = mess + "成功";
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = mess + "失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * CW_INOUTMONEY新增页面跳转
     * 
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cwInoutmoney.getId())) {
            cwInoutmoney = cwInoutmoneyService.getEntity(CwInoutmoneyEntity.class, cwInoutmoney.getId());
            req.setAttribute("cwInoutmoneyPage", cwInoutmoney);
        }
        TSUser u = ResourceUtil.getSessionUser();
        String userName = u.getUserName();
        req.setAttribute("requsername", userName);
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(
                0, 15);
        req.setAttribute("reqseqno", uuid);
        return new ModelAndView("com/jeecg/demo/cwInoutmoney-add");
    }

    /**
     * CW_INOUTMONEY编辑页面跳转
     * 
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cwInoutmoney.getId())) {
            cwInoutmoney = cwInoutmoneyService.getEntity(
                    CwInoutmoneyEntity.class, cwInoutmoney.getId());
            req.setAttribute("cwInoutmoneyPage", cwInoutmoney);
            String tradercode = cwInoutmoney.getTradercode();
            List<TraderEntity> list = systemService.findByProperty(
                    TraderEntity.class, "tradecode", tradercode);
            if (list.size() > 0) {
                String fullname = list.get(0).getFullname();
                req.setAttribute("tradername", fullname);
            }
        }
        return new ModelAndView("com/jeecg/demo/cwInoutmoney-update");
    }

    /**
     * 导入功能跳转
     * 
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "cwInoutmoneyController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     * 
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CwInoutmoneyEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                cwInoutmoney, request.getParameterMap());
        List<CwInoutmoneyEntity> cwInoutmoneys = this.cwInoutmoneyService
                .getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "CW_INOUTMONEY");
        modelMap.put(NormalExcelConstants.CLASS, CwInoutmoneyEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams(
                "CW_INOUTMONEY列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cwInoutmoneys);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     * 
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CwInoutmoneyEntity cwInoutmoney,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "CW_INOUTMONEY");
        modelMap.put(NormalExcelConstants.CLASS, CwInoutmoneyEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams(
                "CW_INOUTMONEY列表", "导出人:"
                        + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request,
            HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CwInoutmoneyEntity> listCwInoutmoneyEntitys = ExcelImportUtil
                        .importExcel(file.getInputStream(),
                                CwInoutmoneyEntity.class, params);
                for (CwInoutmoneyEntity cwInoutmoney : listCwInoutmoneyEntitys) {
                    cwInoutmoneyService.save(cwInoutmoney);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

}
